<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="startTime" prop="startTime">
        <el-select v-model="queryParams.startTime" placeholder="时间">
          <el-option v-for="(name,key) in timeSelections" :key="key" :value="name" :label="key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="消息类型" prop="msgTypes">
        <el-select v-model="queryParams.msgTypes" placeholder="消息类型">
          <el-option value=" " label="不限类型"></el-option>
          <el-option value="text,image,voice,shortvideo,video,news,music,location,link" label="消息"></el-option>
          <el-option value="event,transfer_customer_service" label="事件"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div v-loading="loading">
      <div class="msg-item" v-for="(msg,index) in  msgList" :key="index">
        <div class="avatar"><el-avatar shape="square" :size="60" :src="getUserInfo(msg.openid).headimgurl"></el-avatar></div>
        <div class="item-content">
          <div class="flex justify-between margin-bottom">
            <div class="text-cut">{{getUserInfo(msg.openid).nickname || '--'}}</div>
            <div>{{msg.openid}}</div>
            <div>{{$moment(msg.createTime).calendar()}}</div>
            <div class="reply-btn">
              <div v-if="canReply(msg.createTime)" @click="replyHandle(msg.openid)" class="el-icon-s-promotion">回复</div>
            </div>
          </div>
          <wx-msg-preview :msg="msg" singleLine></wx-msg-preview>
        </div>
      </div>
    </div>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 弹窗, 消息回复 -->
    <msg-reply ref="wxMsgReply" @success="onReplyed"></msg-reply>
  </div>
</template>

<script>
import { listMsg, delMsg, } from "@/api/wx/msg";
import { listByIds } from "@/api/wx/user";
import MsgReply from './msg-reply';
import WxMsgPreview from '@/components/wx-msg-preview';
const TIME_FORMAT = 'YYYY/MM/DD hh:mm:ss'
export default {
  name: "Msg",
  data() {
    return {
      timeSelections:{
        '近24小时':this.$moment().subtract(1, 'days').format(TIME_FORMAT),
        '近3天': this.$moment().subtract(3, 'days').format(TIME_FORMAT),
        '近7天': this.$moment().subtract(7, 'days').format(TIME_FORMAT),
        '近30天': this.$moment().subtract(30, 'days').format(TIME_FORMAT),
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 微信消息表格数据
      msgList: [],
      userDataList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startTime: this.$moment().subtract(1, 'days').format(TIME_FORMAT),
        msgTypes: ' '
      },
      // 默认排序
      defaultSort: {prop: 'create_time', order: 'descending'}
    };
  },
  components: {
    MsgReply, WxMsgPreview
  },
  created() {
    this.queryParams.orderByColumn = this.defaultSort.prop;
    this.queryParams.isAsc = this.defaultSort.order;
    this.getList();
  },
  methods: {
    /** 查询微信消息列表 */
    getList() {
      this.loading = true;
      listMsg(this.queryParams).then(response => {
        this.msgList = response.rows;
        this.total = response.total;
        this.refreshUserList(this.msgList)
        this.loading = false;
      });
    },
    refreshUserList(msgList){
      let openidList=msgList.map(msg=>msg.openid).filter(openid=>!this.userDataList.some(u=>u.openid==openid))
      if(!openidList.length)return
      openidList = Array.from(new Set(openidList))//去重
      listByIds(openidList).then(response => {
        this.userDataList = this.userDataList.concat(response.data)
      });
    },
    getUserInfo(openid){
      return this.userDataList.find(u=>u.openid==openid) || {nickname:'--',headimgurl:''}
    },
    // 是否可回复，24小时内可回复
    canReply(time){
      return new Date(time).getTime()>new Date().getTime()-24*60*60*1000
    },
    // 回复消息
    replyHandle(openid) {
      this.$nextTick(() => {
        this.$refs.wxMsgReply.init(openid)
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    onReplyed(replyMsg){
      this.msgList.unshift({
        openid : replyMsg.openid,
        msgType : replyMsg.replyType,
        detail : {
          content : replyMsg.replyContent
        },
        inOut : 1,
        createTime : new Date()
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除微信消息编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delMsg(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wx/msg/export', {
        ...this.queryParams
      }, `msg_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
  .msg-item{
    border: 1px solid #DCDFE6;
    display: flex;
    justify-content: flex-start;
    align-items: top;
    margin-top: 20px;
    padding: 10px 20px;
  }
  .avatar{
    flex: 0;
    display: inline-block;
    min-width: 60px;
    margin-right: 20px;
  }
  .item-content{
    flex: 1;
    line-height: 20px;
    max-width: 100%;
    overflow: hidden;
  }
  .reply-btn{
    width: 50px;
  }
</style>
